package com.seqb.utils;

import com.seqb.common.Constant;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

/**
 * @author lilinshen
 * @title 文件操作工具类
 * @description 请填写相关描述
 * @date 2019/11/11
 */
public class FileUtils {

    /**
     * 上传文件
     */
    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath + fileName);
        out.write(file);
        out.flush();
        out.close();
    }

    /**
     * 下载文件
     */
    public static void downloadFile(String fileName, String uploadPath, HttpServletResponse response) {
        BufferedOutputStream bufferedOutputStream = null;
        BufferedInputStream bufferedInputStream = null;
        try {
            response.setContentType("APPLICATION/OCTET-STREAM");
            response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"",
                    URLEncoder.encode(fileName.replace(" ", "_").replace(":", ""), "UTF-8")));
            String pathName = uploadPath + fileName;
            InputStream inputStream = new FileInputStream(new File(pathName));
            bufferedInputStream = new BufferedInputStream(inputStream);
            OutputStream outputStream = response.getOutputStream();
            bufferedOutputStream = new BufferedOutputStream(outputStream);
            int bytesRead;
            byte[] buffer = new byte[Constant.BYTE_SIZE];
            while ((bytesRead = bufferedInputStream.read(buffer, 0, Constant.BYTE_SIZE)) != -1) {
                bufferedOutputStream.write(buffer, 0, bytesRead);
            }
            // 这里主要关闭。
            bufferedOutputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedOutputStream != null) {
                    bufferedOutputStream.close();
                }
                if (bufferedInputStream != null) {
                    bufferedInputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 删除文件
     */
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 生成文件名
     */
    public static String renameToUuid(String fileName) {
        return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    /**
     * 重命名后缀名
     */
    public static String renameSuffix(String fileName) {
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        if ("gif".equals(suffix)) {
            return fileName.substring(0, fileName.lastIndexOf(".")) + ".png";
        }
        return fileName;
    }

    /**
     * 生成路径信息,根据年月日.
     */
    public static String generatePath() {
        Calendar cal = Calendar.getInstance();
        return new StringBuffer().append(cal.get(Calendar.YEAR)).append("/").append((cal.get(Calendar.MONTH) + 1)).append("/").toString();
    }

    /**
     * 删除文件list
     */
    public static void deleteFiles(List<File> files) {
        if (files != null && files.size() > 0) {
            for (int i = 0, size = files.size(); i < size; i++) {
                files.get(i).delete();
            }
        }
    }

    /**
     * 链接url下载图片
     */
    public static boolean downloadFile(String networkLink, String filePath) {
        DataInputStream dataInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            URL url = new URL(networkLink);
            dataInputStream = new DataInputStream(url.openStream());
            fileOutputStream = new FileOutputStream(new File(filePath));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            int length;
            byte[] buffer = new byte[1024];
            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            byte[] context = output.toByteArray();
            fileOutputStream.write(context);
            dataInputStream.close();
            fileOutputStream.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (dataInputStream != null) {
                    dataInputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}
